package rmhc.api.vk
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.Security;
	import flash.system.System;
	import rmhc.gui.customTrace;
	
	import rmhc.api.ApiWrapper;
	import rmhc.api.tasks.IGetProfilePicture;
	import rmhc.gui.SupplyFunctions;
	
	public class GetProfilePicture extends VkApiTask implements IGetProfilePicture
	{
		protected var pt:VkApiTask;
		protected var lod:Loader;
		protected var btm:BitmapData;
		
		public function GetProfilePicture( wrapper:ApiWrapper , userId:String = null )
		{
			//var p:Object = { "uids" : userId , "fields" : "photo_big" };
			//var p:Object = { "aids" : "-6" };
			
			var p:Object = { };
			if ( userId != null )
			{
				p.uid = userId;
			}else {
				p.uid = (wrapper as VkApi).getUID();
			}
			p.aid = '-6';
			super( wrapper , 'photos.get' , p );
		}
		public function getPicture():BitmapData
		{
			return btm;
		}

		override public function parseData(result:Object):void
		{
			customTrace("GetProfilePicture:parseData: result = " +SupplyFunctions.objectToString(result));
			var loader:Loader = new Loader();
			var photo:Object = result[result.length - 1];
			for (var i:int = 0; i < result.length; i++) 
			{
				if (uint(result[i].created) > uint(photo.created))
					photo = result[i];
			}
			customTrace("GetProfilePicture:parseData: photo = " +SupplyFunctions.objectToString(photo));
			var url:String;
				   if (photo.src_xxbig) {
				 url = photo.src_xxbig;
			} else if (photo.src_xbig) {
				 url = photo.src_xbig;
			} else if (photo.src_big) {
				 url = photo.src_big;
			} else if (photo.src) {
				 url = photo.src;
			} else if (photo.src_small) {
				 url = photo.src_small;
			} else {
				throw(new Error("Error in GetProfilePicture:parseData. не найден URL аватарки:"+SupplyFunctions.objectToString(result[0])));
			}
			customTrace("GetProfilePicture:parseData: url = "+url );
			var request:URLRequest = new URLRequest(url);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_complete);
			loader.load(request , wrapper.getContext() );
			return;
		}
		
		private function loader_complete(e:Event):void 
		{
			var lod:Loader = ( e.target as LoaderInfo ).loader;
			//customTrace("GetProfilePicture:loader_complete:"+SupplyFunctions.objectToString((e.target as LoaderInfo).content));
			btm = ((e.target as LoaderInfo).content as Bitmap).bitmapData;
			/*btm = new BitmapData( lod.width , lod.height , true , 0 );
			var dummy:MovieClip;
			dummy.addChild( lod.content );
			btm.draw( dummy );*/
			onComplete();
		}

	}
}